<?php

/**
* @copyright   (C) 2010 iJoomla, Inc. - All rights reserved.
* @license  GNU General Public License, version 2 (http://www.gnu.org/licenses/gpl-2.0.html) 
* @author  iJoomla.com webmaster@ijoomla.com
* @url   http://www.ijoomla.com/licensing/
* the PHP code portions are distributed under the GPL license. If not otherwise stated, all images, manuals, cascading style sheets, and included JavaScript  
* are NOT GPL, and are released under the IJOOMLA Proprietary Use License v1.0 
* More info at http://www.ijoomla.com/licensing/
*/

defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.modellist');
jimport('joomla.utilities.date');

class iJoomla_SurveysModelNewquestion extends JModel{
		
	function getAllSurveys(){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('title, id');
		$query->from('#__ijoomla_surveys_surveys');
		$query->order("title ASC");
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();		
		return $result;
	}
	
	function getAllPages(){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('title, id');
		$query->from('#__ijoomla_surveys_pages');
		$query->order("title ASC");
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();		
		return $result;
	}
	
	function getColumnsValues(){
		$id = JRequest::getVar("id", "0");
		if($id != "0"){
			$db =& JFactory::getDBO();		
			$query = $db->getQuery(true);
			$query->clear();	
			$query->select('GROUP_CONCAT(distinct c.value order by c.id SEPARATOR \'\n\') as value');
			$query->from('#__ijoomla_surveys_answer_columns as c');
			$query->where("c.question_id =".$id);			
			$db->setQuery($query);		
			$db->query();
			$result = $db->loadAssocList();			
			return $result;
		}
		else{
			return "";
		}
	}
	
	function getMenuDetails($q_id, $m_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();
		$query->select('GROUP_CONCAT(distinct ac.value order by ac.id SEPARATOR \'\n\') as menu_choises, mh.value as heading');
		$query->from('#__ijoomla_surveys_menu_heading mh, #__ijoomla_surveys_answer_columns ac');
		$query->where("mh.order=".$m_id." and ac.menu_order=mh.id and mh.question_id=".$q_id);		
		$db->setQuery($query);	
		$db->query();
		$result = $db->loadAssocList();		
		return $result;
	}
	
	function getQuestionValues(){
		$id = JRequest::getVar("id", "0");
		if($id != "0"){
			$db =& JFactory::getDBO();		
			$query = $db->getQuery(true);
			$query->clear();	
			$query->select('q.*, GROUP_CONCAT(distinct a.value order by a.id asc SEPARATOR \'\n\') as answer_choises');
			$query->from('#__ijoomla_surveys_questions as q');
			$query->join('LEFT', '#__ijoomla_surveys_answers as a ON q.id=a.question_id');
			$query->where("q.id =".$id);
			$query->group("q.id");				
			$db->setQuery($query);
			$db->query();
			$result = $db->loadAssocList();		
			return $result;
		}
		else{
			return "";
		}
	}
	
	function getPages(){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();	
		$query->select('id, title, ordering');
		$query->from('#__ijoomla_surveys_questions');	
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();		
		return $result;
	}
	
	function save(){
		$db =& JFactory::getDBO();		
		$table =& $this->getTable();		
		$return = array();		
		$id = JRequest::getVar("id", "0");				
		
		$all_dates = JRequest::get('post',JREQUEST_ALLOWRAW);
		if(trim($all_dates["constant"]) == ""){
			$all_dates["constant"] = -1;
		}		
		if($all_dates["question_type"] == "1" || $all_dates["question_type"] == "4"){
			$all_dates["orientation"] = "vertical";
		}
		elseif($all_dates["question_type"] == "2" || $all_dates["question_type"] == "5"){
			$all_dates["orientation"] = "horizontal";
		}
		if(isset($all_dates["random_a"]) && $all_dates["random_a"] == NULL){
			$all_dates["random_a"] = "0";
		}				
		
		if($id == "0"){
			$ordering = $this->getMaxOrdering();
			$all_dates["ordering"] = $ordering;
		}
		else{
			unset($all_dates["ordering"]);
		}
		
		$params = $this->getParams();
		$format = $params->general_date;
								
		// Bind the form fields to the news table		
		if (!$table->bind($all_dates)){
			echo $this->_db->getErrorMsg(); exit;
			$this->setError($this->_db->getErrorMsg());
			$return["0"] = false;
		}
		// Make sure the news record is valid
		if (!$table->check()){
			echo $this->_db->getErrorMsg(); exit;		
			$this->setError($this->_db->getErrorMsg());
			$return["0"] = false;
		}		
		// Store the web link table to the database
		if (!$table->store()){
			echo $this->_db->getErrorMsg(); exit;
			$this->setError( $this->_db->getErrorMsg() );
			$return["0"] = false;
		}
		
		$return["0"] = true;
		$return["1"] = $table->id;
		
		$result1 = $this->saveAnswers($all_dates, $table->id);
		if($result1){			
			$result2 = $this->saveAnswersColumns($all_dates, $table->id);
		}
		
		if($all_dates["question_type"]=="8"){			
			$result3 = $this->saveMenusHeadChois($all_dates, $table->id);
			if($result3){
				$result4 = $this->saveAnswersColumnsMenus($all_dates, $table->id);
			}
		}
		else{
			$this->deleteFromMenuHeading($all_dates["id"], $table->id);
		}
		
		return $return;
	}
	
	function saveAnswersColumnsMenus($all_dates, $table_id){		
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->clear();
		$id = $all_dates["id"];
		if($id == "0"){
			$id = $table_id;
		}		
		if(isset($all_dates["question_type"]) && ($all_dates["question_type"] == "8")){
			if($id != "0"){
				if(!$this->inAnswersColumns($id, 1)){
					$allvalues = $all_dates["menu_choices"];
										
					foreach($allvalues as $key_array=>$value_array){
						$values = explode("\n", trim($value_array));						
						foreach($values as $key=>$value){
							if(trim($value) != ""){
								$menu_order = $this->getMenuHeadingId($all_dates["menu_heading"][$key_array], $id);
								if(intval($menu_order) != 0){
									$query->clear();
									$query->insert("#__ijoomla_surveys_answer_columns");
									$query->set("question_id=".$id);
									$query->set("value='".addslashes(trim($value))."'");
									$query->set("menu_order=".intval($menu_order));
									$db->setQuery($query);
									if(!$db->query()){
										return false;
									}
								}	
							}
						}
					}
				}//if exist
				else{
					$sql = "select id from #__ijoomla_surveys_answer_columns where question_id=".$id." order by id";
					$db->setQuery($sql);
					$db->query();
					$old_ids = $db->loadResultArray();
					$values = explode("\n", trim($all_dates["columns"]));					
					foreach($values as $key=>$value){
						if(isset($old_ids[$key])){
							$query->clear();
							$query->update("#__ijoomla_surveys_answer_columns");
							$query->set("value='".addslashes($value)."'");
							$query->where("id=".$old_ids[$key]);
							$db->setQuery($query);		
							if(!$db->query()){
								return false;
							}
							unset($old_ids[$key]);
						}
						else{						
							$query->clear();
							$query->insert("#__ijoomla_surveys_answer_columns");
							$query->set("question_id=".$id);
							$query->set("value='".addslashes($value)."'");
							$query->set("menu_order=0");
							$db->setQuery($query);		
							if(!$db->query()){
								return false;
							}
						}						
					}
					//if old_ids is now bigger then second save (ie. we ahve first time 5 answer and naw we save 2, 3 answers must be deleted)
					if(count($old_ids)>0){
						$query->clear();
						$query->delete("#__ijoomla_surveys_answer_columns");
						$query->where("id in(".implode(",",$old_ids).")");
						$db->setQuery($query);		
						if(!$db->query()){
							return false;
						}
					}
				}
			}//is a new question
			else{
				$values = explode("\n", $all_dates["columns"]);					
				foreach($values as $key=>$value){
					if(trim($value) != ""){
						$menu_order = $this->getMenuHeadingId($all_dates["menu_heading"][$key], $id);
						$query->clear();
						$query->insert("#__ijoomla_surveys_answer_columns");
						$query->set("question_id=".$id);
						$query->set("value='".addslashes($value)."'");
						$query->set("menu_order=".intval($menu_order));
						$db->setQuery($query);		
						if(!$db->query()){
							return false;
						}
					}
				}
			}
		}
		else{
			$this->deleteFromAnswerColumn($id, 1);
		}
		return true;
	}
	
	function saveMenusHeadChois($all_dates, $table_id){		
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->clear();
		$id = $all_dates["id"];
		
		if($id == "0"){
			$id = $table_id;
		}
		
		if($id != "0"){
			if(!$this->inMenuHeading($id)){
				if($all_dates["nums_menu_heading"] != "0"){
					for($i=1; $i<=$all_dates["nums_menu_heading"]; $i++){
						if(trim($all_dates["menu_heading"][$i]) != ""){							
							$query = "insert into #__ijoomla_surveys_menu_heading (`question_id`, `value`, `order`) values (".$id.", '".trim(addslashes($all_dates["menu_heading"][$i]))."', ".$i.")";							
							$db->setQuery($query);		
							if(!$db->query()){
								return false;
							}
						}
					}
				}
			}
			else{												
				$sql = "select id, value from #__ijoomla_surveys_menu_heading where question_id=".$id." order by id asc";
				$db->setQuery($sql);
				$db->query();
				$old_result = $db->loadAssocList(); 
				
				$i = 1;
				foreach($all_dates["menu_heading"] as $key=>$value){
					if(isset($old_result[$i-1])){
						$sql = "update #__ijoomla_surveys_menu_heading set value='".trim(addslashes($all_dates["menu_heading"][$i]))."' where question_id=".$id." and id=".$old_result[$i-1]["id"];
						$db->setQuery($sql);
						$db->query();
						unset($old_result[$i-1]);	
					}
					else{
						if(trim($all_dates["menu_heading"][$i]) != ""){
							$sql = "insert into #__ijoomla_surveys_menu_heading (`question_id`, `value`, `order`) values (".$id.", '".addslashes(trim($all_dates["menu_heading"][$i]))."', ".$i.")";
							$db->setQuery($sql);
							$db->query();
						}
					}										
					$i++;
				}
								
				if(is_array($old_result) && count($old_result)>0){
					foreach($old_result as $key=>$value){						
						$query->clear();
						$query->delete("#__ijoomla_surveys_menu_heading");
						$query->where("id=".$value["id"]);
						$db->setQuery($query);
						$db->query();
					}
				}							
			}
		}		
		return true;
	}
	
	function saveAnswersColumns($all_dates, $table_id){		
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->clear();
		$id = $all_dates["id"];
		if($id == "0"){
			$id = $table_id;
		}
		if(isset($all_dates["question_type"]) && ($all_dates["question_type"] == "6" || $all_dates["question_type"] == "7")){					
			if($id != "0"){
				if(!$this->inAnswersColumns($id, 0)){
					$values = explode("\n", trim($all_dates["columns"]));				
					foreach($values as $key=>$value){
						if(trim($value) != ""){
							$query->clear();
							$query->insert("#__ijoomla_surveys_answer_columns");
							$query->set("question_id=".$id);
							$query->set("value='".addslashes($value)."'");
							$query->set("menu_order=0");												
							$db->setQuery($query);		
							if(!$db->query()){
								return false;
							}						
						}
					}
				}//if exist
				else{
					$sql = "select id from #__ijoomla_surveys_answer_columns where question_id=".$id." order by id";
					$db->setQuery($sql);
					$db->query();
					$old_ids = $db->loadResultArray();
					$values = explode("\n", trim($all_dates["columns"]));					
					foreach($values as $key=>$value){
						if(isset($old_ids[$key])){
							$query->clear();
							$query->update("#__ijoomla_surveys_answer_columns");
							$query->set("value='".addslashes($value)."'");
							$query->where("id=".$old_ids[$key]);
							$db->setQuery($query);		
							if(!$db->query()){
								return false;
							}
							unset($old_ids[$key]);
						}
						else{						
							$query->clear();
							$query->insert("#__ijoomla_surveys_answer_columns");
							$query->set("question_id=".$id);
							$query->set("value='".addslashes($value)."'");
							$query->set("menu_order=0");
							$db->setQuery($query);		
							if(!$db->query()){
								return false;
							}
						}						
					}
					//if old_ids is now bigger then second save (ie. we ahve first time 5 answer and naw we save 2, 3 answers must be deleted)					
					if(count($old_ids)>0){
						$query->clear();
						$query->delete("#__ijoomla_surveys_answer_columns");
						$query->where("id in(".implode(",",$old_ids).")");
						$db->setQuery($query);		
						if(!$db->query()){
							return false;
						}
					}
				}
			}//is a new question
			else{
				$values = explode("\n", $all_dates["columns"]);					
				foreach($values as $key=>$value){
					if(trim($value) != ""){
						$query->clear();
						$query->insert("#__ijoomla_surveys_answer_columns");
						$query->set("question_id=".$id);
						$query->set("value='".addslashes($value)."'");
						$query->set("menu_order=0");
						$db->setQuery($query);		
						if(!$db->query()){
							return false;
						}
					}
				}
			}
		}
		else{
			$this->deleteFromAnswerColumn($id, 0);
		}
		return true;
	}
	
	function saveAnswers($all_dates, $table_id){
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->clear();
		$id = $all_dates["id"];
		if($id == "0"){
			$id = $table_id;
		}		
		if(isset($all_dates["question_type"]) && ($all_dates["question_type"] != "11" && $all_dates["question_type"] != "0")){
			if($id != "0"){
				if(!$this->isInAnswers($id)){
					$values = explode("\n", trim($all_dates["answer"]));					
					foreach($values as $key=>$value){
						if(trim($value) != ""){
							$query->clear();
							$query->insert("#__ijoomla_surveys_answers");
							$query->set("question_id=".$id);
							$query->set("value='".addslashes($value)."'");
							$db->setQuery($query);		
							if(!$db->query()){
								return false;
							}
						}
					}
				}
				else{
					$sql = "select id from #__ijoomla_surveys_answers where question_id=".$id." order by id";
					$db->setQuery($sql);
					$db->query();
					$old_ids = $db->loadResultArray();					
					$values = explode("\n", $all_dates["answer"]);					
					foreach($values as $key=>$value){
						if(isset($old_ids[$key])){
							$query->clear();
							$query->update("#__ijoomla_surveys_answers");
							$query->set("value='".addslashes($value)."'");
							$query->where("id=".$old_ids[$key]);
							$db->setQuery($query);
							if(!$db->query()){
								return false;
							}
							unset($old_ids[$key]);
						}
						else{
							$query->clear();
							$query->insert("#__ijoomla_surveys_answers");
							$query->set("question_id=".$id);
							$query->set("value='".addslashes($value)."'");
							$db->setQuery($query);		
							if(!$db->query()){
								return false;
							}
						}						
					}
					//if old_ids is now bigger then second save (ie. we ahve first time 5 answer and naw we save 2, 3 answers must be deleted)
					if(count($old_ids)>0){
						$query->clear();
						$query->delete("#__ijoomla_surveys_answers");
						$query->where("id in(".implode(",",$old_ids).")");
						$db->setQuery($query);		
						if(!$db->query()){
							return false;
						}
					}
				}
			}//the question is new
			else{
				$values = explode("\n", trim($all_dates["answer"]));					
				foreach($values as $key=>$value){
					if(trim($value) != ""){
						$query->clear();
						$query->insert("#__ijoomla_surveys_answers");
						$query->set("question_id=".$id);
						$query->set("value='".addslashes($value)."'");
						$db->setQuery($query);		
						if(!$db->query()){
							return false;
						}
					}	
				}
			}
		}//we doesn't need answers in database if is another qestion type
		else{
			$this->deleteFromAnswer($id);
		}
		return true;
	}
	
	function deleteFromAnswer($id){
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->clear();
		$query->delete("#__ijoomla_surveys_answers");
		$query->where("question_id=".$id);
		$db->setQuery($query);		
		if(!$db->query()){
			return false;
		}
		return true;
	}
	
	function deleteFromMenuHeading($id){
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->clear();
		
		if($this->inMenuHeading($id)){
			$query->delete("#__ijoomla_surveys_menu_heading");
			$query->where("question_id=".$id);
			$db->setQuery($query);		
			if(!$db->query()){
				return false;
			}
			return true;
		}
	}
	
	function deleteFromAnswerColumn($id, $val){
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$order = "";
		if($val==0){
			$order = "=0";
		}
		else{
			$order = "<>0";
		}
		$query->clear();
		$query->delete("#__ijoomla_surveys_answer_columns");
		$query->where("question_id=".$id." and menu_order".$order);
		$db->setQuery($query);		
		if(!$db->query()){
			return false;
		}
		return true;
	}
	
	function isInAnswers($id){
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->clear();
		$query->select("count(*)");
		$query->from("#__ijoomla_surveys_answers");
		$query->where("question_id=".$id);
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadResult();
		if($result > 0){
			return true;
		}
		else{
			return false;
		} 
	}
	
	function inMenuHeading($id){
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->clear();
		$query->select("count(*)");
		$query->from("#__ijoomla_surveys_menu_heading");
		$query->where("question_id=".$id);
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadResult();
		if($result > 0){
			return true;
		}
		else{
			return false;
		} 
	}
	
	function getMenuHeadingId($value, $q_id){
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$query->clear();
		$query->select("id");
		$query->from("#__ijoomla_surveys_menu_heading");
		$query->where("value='".addslashes(trim($value))."' and question_id=".$q_id);
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadResult();		
		return $result;
	}
	
	function inAnswersColumns($id, $val){
		$db =& JFactory::getDBO();
		$query = $db->getQuery(true);
		$order = "";
		if($val==0){
			$order = "=0";
		}
		else{
			$order = "<>0";
		}
		$query->clear();
		$query->select("count(*)");
		$query->from("#__ijoomla_surveys_answer_columns");
		$query->where("question_id=".$id." and menu_order".$order);
		$db->setQuery($query);	
		$db->query();
		$result = $db->loadResult();
		if($result > 0){
			return true;
		}
		else{
			return false;
		} 
	}
	
	function getMaxOrdering(){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('max(ordering)');
		$query->from('#__ijoomla_surveys_questions');
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadResult();
		return (int)($result)+1;
	}
	
	function getParams(){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('params');
		$query->from('#__extensions');
		$query->where("element='com_surveys'");
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadResult();
		$array = json_decode($result);
		return $array;
	}
	
}

?>